package com.sikadwafastdaisfondturbo.pretloan.ui.permission

import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.sikadwa.lib_permission.OnPermissionCallback
import com.sikadwa.lib_permission.Permission
import com.sikadwa.lib_permission.XXPermissions
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.PermissionReasonAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.ActivityPermissionReasonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.TipsDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaAmountPlusHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.SikadwaKefuConfigHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.HttpHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.rv.LinearDecoration
import org.json.JSONArray
import org.json.JSONObject

/**
 * 权限说明列表
 */
class PermissionReasonActivity : ProActivity() {
    private val INTENT_KEY_AMOUNT = "amount"
    lateinit var binding: ActivityPermissionReasonBinding
    private var itemAdapter: PermissionReasonAdapter? = null

    override fun getRootView(): View {
        binding = ActivityPermissionReasonBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        binding.permissionContentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initPermissionListView()

        binding.imgLang.visibility = View.GONE
        if (Configs.isTanzania()){
            binding.imgLang.visibility = View.VISIBLE
        }
    }

    override fun initListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //切换语言
        binding.imgLang.setOnClickListener {
            showSikadwaProLangDialog("Permission Page", onCheckSuccess = {

            })
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Permission Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Permission Page")
        }

//        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
//            when (isChecked) {
//                true -> {
//                    binding.btnPermissionAgree.isEnabled = true
//                }
//                false -> {
//                    binding.btnPermissionAgree.isEnabled = false
//                }
//            }
//        }

        //拒绝
        binding.btnPermissionDeny.setOnClickListener {
            Configs.saveSPInt(Configs.SPKEY.SIKADWA_PERMISSION_REASON_STATUS,-1)
            addEvent(EventType.CLICK.CLICK_PERMISSION_DENY,"Permission Page")

            val intent = intent
            intent.putExtra("isPermissionAgree",false)
            setResult(RESULT_OK,intent)
            finish()
        }

        //同意权限
        binding.btnPermissionAgree.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_PERMISSION_AGREE,"Permission Page")
            if (!binding.checkBox.isChecked){
                showPermissionAgreedDialog()
                return@setOnClickListener
            }
            Configs.saveSPInt(Configs.SPKEY.SIKADWA_PERMISSION_REASON_STATUS,1)
            loadSikadwaPermissionAction()
        }
    }

    override fun initData() {
        showSikadwaGuideStepViews()

        val itemList = arrayListOf<JSONObject>()
        itemList.add(takeSikadwaMESAGItem())
        itemList.add(takeSikadwaDeviceItem())
        itemList.add(takeSikadwaCameraItem())
        itemList.add(takeSikadwaStorageItem())
        itemList.add(takeSikadwaPhoneBookItem())
        itemList.add(takeSikadwaPhotoAlbumItem())
        itemAdapter?.data = itemList
    }

    /**
     * 初始化权限列表
     */
    private fun initPermissionListView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        itemAdapter = PermissionReasonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = itemAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 显示引导额度提升/通过率
     */
    private fun showSikadwaGuideStepViews(){
        binding.textGuideStepIndex.text = "1"
        binding.textGuideStepTitle.text = getString(R.string.permissions_guide_step_permission)
        val guideType = SikadwaKefuConfigHelper.takeSikadwaGuideType()
        when(guideType){
            "showLoanAmount" -> {//loan amount
                binding.textGuideStepType.text = getString(R.string.permissions_guide_step_loan_amount)
                binding.textGuideStepTips.text = getString(R.string.permissions_guide_step_amount_complete_tips)
                //外显额度
                val showAmount = getLimitAmount()
                //获取权限页显示的额度
                val perAmount = SikadwaAmountPlusHelper.takeSikadwaGuideStepPermissionLoanAmount(showAmount)
                binding.stepSeekbar.min = 0f
                binding.stepSeekbar.max = showAmount.toFloat()
                binding.stepSeekbar.setProgress(perAmount)
                binding.stepSeekbar.setProgressValueTypeInt(true)
            }
            else -> {//pass rate
                binding.textGuideStepType.text = getString(R.string.permissions_guide_step_pass_rate)
                binding.textGuideStepTips.text = getString(R.string.permissions_guide_step_pass_rate_complete_tips)
                //获取权限页显示的通过率
                val perPassRate = SikadwaAmountPlusHelper.takeSikadwaGuideStepPermissionPassRate()
                binding.stepSeekbar.min = 0f
                binding.stepSeekbar.max = 100f
                binding.stepSeekbar.setProgress(perPassRate)
                binding.stepSeekbar.setProgressValueTypeInt(false)
            }
        }
    }

    /**
     * 获取额度
     */
    private fun getLimitAmount(): String{
        intent.extras?.let {
            return it.getString(INTENT_KEY_AMOUNT,"0").toString()
        }
        return "0"
    }

    /**
     * 阅读与同意
     */
    private fun showPermissionAgreedDialog(){
        val tipsDialog = TipsDialog(this,"Permission Page",object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnOk){
                    binding.checkBox.isChecked = true
                    binding.btnPermissionAgree.callOnClick()
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setTipsTitle(getString(R.string.tips_kind))
        tipsDialog.setTips(getString(R.string.permission_agree_tips))
    }

    /**
     * 申请权限
     */
    private fun loadSikadwaPermissionAction(){
        XXPermissions.with(this)
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                @SuppressLint("UnsafeIntentLaunch")
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        val intent = intent
                        intent.putExtra("isPermissionAgree",true)
                        setResult(RESULT_OK,intent)
                        finish()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(this@PermissionReasonActivity,Permission.READ_SMS)
                }
            })
    }

    /**
     * sms
     */
    private fun takeSikadwaMESAGItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("permission", Permission.READ_SMS)
        item.put("title", getString(R.string.permission_sms_title))
        item.put("icon",R.mipmap.img_permission_reason_sms_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", getString(R.string.permission_sms_why))
        obj1.put("des", getString(R.string.permission_sms_why_des))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", getString(R.string.permission_sms_can_do))
        obj2.put("des", getString(R.string.permission_sms_can_do_des))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", getString(R.string.permission_sms_data_safety))
        obj3.put("des", getString(R.string.permission_sms_data_safety_des1))
        msgArray.put(obj3)

        item.put("msgList",msgArray)
        return item
    }

    /**
     * device
     */
    private fun takeSikadwaDeviceItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("permission", getString(R.string.permission_device_title))
        item.put("title", getString(R.string.permission_device_title))
        item.put("icon",R.mipmap.img_permission_reason_device_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_device_des1))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", "")
        obj2.put("des", getString(R.string.permission_device_des2))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", "")
        obj3.put("des", getString(R.string.permission_device_des3))
        msgArray.put(obj3)

        val obj4 = JSONObject()
        obj4.put("title", "")
        obj4.put("des", getString(R.string.permission_device_des4))
        msgArray.put(obj4)

        val obj5 = JSONObject()
        obj5.put("title", "")
        obj5.put("des", getString(R.string.permission_device_des5))
        msgArray.put(obj5)
        item.put("msgList",msgArray)
        return item
    }

    /**
     * camera
     */
    private fun takeSikadwaCameraItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",true)
        item.put("permission", Permission.CAMERA)
        item.put("title", getString(R.string.permission_camera_title))
        item.put("titleReason",getString(R.string.permission_camera_title))
        item.put("iconReason",R.mipmap.img_permission_phonestatus)
        item.put("icon",R.mipmap.img_permission_reason_camera_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_camera_des1))
        msgArray.put(obj1)

        val obj2 = JSONObject()
        obj2.put("title", "")
        obj2.put("des", getString(R.string.permission_camera_des2))
        msgArray.put(obj2)

        val obj3 = JSONObject()
        obj3.put("title", "")
        obj3.put("des", getString(R.string.permission_camera_des3))
        msgArray.put(obj3)
        item.put("msgList",msgArray)
        return item
    }

    /**
     * storage
     */
    private fun takeSikadwaStorageItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("permission", getString(R.string.permission_storage_title))
        item.put("title", getString(R.string.permission_storage_title))
        item.put("icon",R.mipmap.img_permission_reason_storage_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_storage_des))
        msgArray.put(obj1)
        item.put("msgList",msgArray)
        return item
    }

    /**
     * contact
     */
    private fun takeSikadwaPhoneBookItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("permission", getString(R.string.permission_contact_title))
        item.put("title", getString(R.string.permission_contact_title))
        item.put("icon",R.mipmap.img_permission_reason_contact_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_contact_des))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }

    /**
     * album
     */
    private fun takeSikadwaPhotoAlbumItem(): JSONObject {
        val item = JSONObject()
        item.put("isSystem",false)
        item.put("permission", getString(R.string.permission_album_title))
        item.put("title", getString(R.string.permission_album_title))
        item.put("icon",R.mipmap.img_permission_reason_album_icon)
        val msgArray = JSONArray()
        val obj1 = JSONObject()
        obj1.put("title", "")
        obj1.put("des", getString(R.string.permission_album_des))
        msgArray.put(obj1)

        item.put("msgList",msgArray)
        return item
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_PERMISSION_END)
    }
}